# Copyright (c) 2024, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe
from frappe.model.document import Document

class PaymentLedgerMapping(Document):
    def validate(self):
        """验证文档数据"""
        self.validate_company()
        self.set_name_field()
        self.validate_duplicate_accounts()

    def validate_company(self):
        """确保公司字段不为空"""
        if not self.company:
            frappe.throw(_("Company is mandatory. Please select a company first."))

    def set_name_field(self):
        """强制设置名称字段，避免为空"""
        if not self.name or self.name == "New Payment Ledger Mapping":
            self.name = f"Payment Ledger Mapping - {self.company}"

    def validate_duplicate_accounts(self):
        """验证子表中没有重复的账户"""
        accounts = []
        for item in self.account_mappings:
            if item.account in accounts:
                frappe.throw(_("Account {0} is added multiple times. Please remove duplicates.").format(item.account))
            accounts.append(item.account)

    def on_update(self):
        """更新后清除缓存"""
        frappe.cache().delete_key(f"payment_ledger_mapping:{self.company}")

    @staticmethod
    def get_mappings_for_company(company):
        """获取指定公司的映射关系（带缓存）"""
        cache_key = f"payment_ledger_mapping:{company}"
        mappings = frappe.cache().get(cache_key)
        
        if not mappings:
            if frappe.db.exists("Payment Ledger Mapping", {"company": company}):
                doc = frappe.get_doc("Payment Ledger Mapping", {"company": company})
                mappings = {item.account: item.report_item for item in doc.account_mappings}
                frappe.cache().setex(cache_key, 3600, mappings)  # 缓存1小时
            else:
                mappings = {}
        
        return mappings
    